<template>
  <div class="body">
    <div class="container">
      <!-- 页面标题 -->
      <div class="text-center mb-8">
        <h1 class="page-title">
          <i class="fa fa-users text-primary mr-2"></i>家庭成员信息表单
        </h1>
      </div>

      <!-- 表单卡片 -->
      <div class="form-card mb-8">
        <form @submit.prevent="submitForm">
          <!-- 基本信息 -->
          <div class="section mb-6">
            <h2 class="section-title">
              <i class="fa fa-user-circle text-primary mr-2"></i>基本信息
            </h2>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="form-group">
                <label for="name" class="form-label">
                  <span class="text-danger">*</span>姓名
                </label>
                <el-input
                  id="name"
                  v-model="member.memberName"
                  placeholder="请输入姓名"
                  class="form-input"
                  clearable
                ></el-input>
              </div>

              <div class="form-group">
                <label for="gender" class="form-label">
                  <span class="text-danger">*</span>性别
                </label>
                <el-select
                  id="gender"
                  v-model="member.gender"
                  placeholder="请选择性别"
                  class="form-select"
                  clearable
                >
                  <el-option label="男" value="M" />
                  <el-option label="女" value="F" />
                </el-select>
              </div>

              <div class="form-group">
                <label for="idCard" class="form-label">
                  <span class="text-danger">*</span>身份证号
                </label>
                <el-input
                  id="idCard"
                  v-model="member.idCard"
                  placeholder="请输入18位身份证号"
                  class="form-input"
                  clearable
                ></el-input>
              </div>

              <div class="form-group">
                <label for="relation" class="form-label">
                  <span class="text-danger">*</span>与户主关系
                </label>
                <el-select
                  id="relation"
                  v-model="member.relation"
                  placeholder="请选择与户主关系"
                  class="form-select"
                  clearable
                >
                  <el-option label="本人" value="本人" />
                  <el-option label="配偶" value="配偶" />
                  <el-option label="子女" value="子女" />
                  <el-option label="父母" value="父母" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </div>

              <!-- 修改：将民族改为文本输入框 -->
              <div class="form-group">
                <label for="ethnicity" class="form-label">
                  民族
                </label>
                <el-input
                  id="ethnicity"
                  v-model="member.nation"
                  placeholder="请输入民族"
                  class="form-input"
                  clearable
                ></el-input>
              </div>

              <div class="form-group">
                <label for="politicalStatus" class="form-label">
                  政治面貌
                </label>
                <el-select
                  id="politicalStatus"
                  v-model="member.politicalStatus"
                  placeholder="请选择政治面貌"
                  class="form-select"
                  clearable
                >
                  <el-option label="群众" value="群众" />
                  <el-option label="共青团员" value="共青团员" />
                  <el-option label="中共党员" value="中共党员" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </div>

              <div class="form-group">
                <label for="educationStatus" class="form-label">
                  文化程度
                </label>
                <el-select
                  id="educationStatus"
                  v-model="member.education"
                  placeholder="请选择文化程度"
                  class="form-select"
                  clearable
                >
                  <el-option label="小学" value="小学" />
                  <el-option label="初中" value="初中" />
                  <el-option label="高中" value="高中" />
                  <el-option label="大专" value="大专" />
                  <el-option label="本科" value="本科" />
                  <el-option label="研究生及以上" value="研究生及以上" />
                </el-select>
              </div>

              <div class="form-group">
                <label for="healthStatus" class="form-label">
                  健康状况
                </label>
                <el-select
                  id="healthStatus"
                  v-model="member.health"
                  placeholder="请选择健康状况"
                  class="form-select"
                  clearable
                >
                  <el-option label="健康" value="健康" />
                  <el-option label="一般" value="一般" />
                  <el-option label="较差" value="较差" />
                  <el-option label="有残疾" value="有残疾" />
                </el-select>
              </div>

              <div class="form-group md:col-span-2">
                <label for="skills" class="form-label">
                  掌握技能
                </label>
                <el-input
                  id="skills"
                  v-model="member.laborskills"
                  placeholder="请输入掌握的技能，多个技能请用逗号分隔"
                  class="form-input"
                  type="textarea"
                  :rows="3"
                  clearable
                ></el-input>
              </div>
            </div>
          </div>

          <!-- 表单操作区 -->
          <div class="form-actions">
            <div class="validation-hint" v-if="validationMessage">
              {{ validationMessage }}
            </div>
            <div class="buttons">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button type="danger" @click="resetForm">重置</el-button>
            </div>
          </div>
        </form>
      </div>

      <!-- 提交结果显示 -->
      <div v-if="submissionResult" class="result-card">
        <h3 class="result-title">
          <i class="fa fa-check-circle text-success mr-2"></i>提交结果
        </h3>
        <div class="result-content">
          <pre class="result-text">{{ submissionResult }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { addFamilyMember } from "@/api/application"
const router = useRouter();

// 家庭成员数据
const member = reactive({
  declarationId:'1',
  memberName: '',
  gender: '',
  idCard: '',
  relation: '',
  nation: '', // 民族改为文本输入
  politicalStatus: '',
  education: '',
  health: '',
  laborskills: ''
});

// 表单验证消息
const validationMessage = ref('');

// 提交结果
const submissionResult = ref('');

// 页面加载时从localStorage读取数据
onMounted(() => {
  console.log(`memberstart--->`,member)
  const savedData = localStorage.getItem('familyMemberData');
  const savedApplication=localStorage.getItem("application");
  if (savedData) {
    try {
      member.value = JSON.parse(savedData);
    } catch (error) {
      console.error('Failed to parse saved form data:', error);
      ElMessage.error('加载表单数据失败');
    }
  }
});

// 表单提交处理
const submitForm = () => {
  validationMessage.value = ''; // 清空之前的验证消息

  // 定义必填字段
  const requiredFields = ['memberName', 'gender', 'idCard', 'relation'];

  // 表单验证
  for (const key of requiredFields) {
    if (!member[key]) {
      validationMessage.value = '请填写所有带 * 的必填字段';
      return;
    }
  }

  // 身份证格式简单验证
  const idCardPattern = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!idCardPattern.test(member.idCard)) {
    validationMessage.value = '请输入有效的18位身份证号码';
    return;
  }

  addFamilyMember(member).then(res => {
      if (res.code == 2000) {
        ElMessage.success('添加成功')
          try {
            localStorage.setItem('familyMemberData', JSON.stringify(member));
            console.log(`member------>`,member)
            router.push("/application")
          } catch (e) {
              console.error('保存表单数据失败:', e);
              ElMessage.error('保存数据失败，请稍后重试！');
              return; // 保存失败则不跳转
          }
      }
    })
  // 成功提示
  // ElMessage.success('家庭成员信息提交成功！');
  // router.push('/application');
};

// 返回编辑页面
const goBack = () => {
  // 保留数据在localStorage中
  // 跳转到表单页面
  router.push('/family-form');
};

// 重置表单
const resetForm = () => {
  // 重置表单数据
  member.value = {
    memberName: '',
    gender: '',
    idCard: '',
    relation: '',
    nation: '', // 民族改为文本输入
    politicalStatus: '',
    education: '',
    health: '',
    laborskills: ''
  };
  
  // 清空localStorage
  localStorage.removeItem('familyMemberData');
  
  // 清空提交结果和验证消息
  submissionResult.value = '';
  validationMessage.value = '';
  
  // 重置HTML表单元素
  const form = document.querySelector('form');
  if (form) form.reset();
};
</script>

<style scoped>
/* 颜色定义 */
.text-danger {
  color: #ef4444;
}

.text-warning {
  color: #f59e0b;
}

.text-primary {
  color: #2563eb;
}

.text-success {
  color: #10b981;
}

/* 布局组件 */
.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.form-card, .result-card {
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  padding: 1.5rem 2rem;
  margin-bottom: 2rem;
  transition: all 0.3s ease;
}

.form-card:hover, .result-card:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.section {
  margin-bottom: 1.5rem;
}

/* 标题样式 */
.page-title {
  font-size: clamp(1.5rem, 3vw, 2.5rem);
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 0.5rem;
  text-align: center;
}

.section-title, .result-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
}

/* 表单元素样式 */
.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  margin-bottom: 0.25rem;
}

/* 表单操作区样式 */
.form-actions {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
}

@media (min-width: 640px) {
  .form-actions {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    justify-content: center;
  }
}

.validation-hint {
  font-size: 0.875rem;
  color: #6b7280;
}

.buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

/* 结果显示样式 */
.result-content {
  background-color: #f9fafb;
  border-radius: 0.375rem;
  padding: 1rem;
  overflow-x: auto;
}

.result-text {
  color: #4b5563;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>